import axios, { AxiosRequestConfig } from 'axios'
import router from '../router/index'
import { ElMessage } from 'element-plus'

const http = axios.create({
    baseURL: 'http://localhost:3000',
})

// let router = useRouter();


// 响应拦截器
http.interceptors.response.use(resp => {
    if (resp.status === 401 || resp.data.code === 401) {
        router.push({
            path: '/login'
        })
        
        ElMessage.warning('请退出重新登录！')
        resp
    }
    
    return Promise.resolve(resp);
    
    
}, error => {
    if (error.response || error.response?.status == 401) {
        ElMessage.warning('请退出重新登录！')
        router.push({
            path: '/login',
        });

        sessionStorage.removeItem('login-user-info');
    }

    return Promise.reject(error);
})

// 请求拦截器
http.interceptors.request.use((config: AxiosRequestConfig) => {
    let token:string | null = window.sessionStorage.getItem('token');

    if (token && config.headers) {
        config.headers.authorization = 'Bearer ' + token;
    }

    return config;
}, error => {
    return Promise.reject(error);
})

export default http;